package tech.yingchuan.blogs.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import tech.yingchuan.blogs.authentication.SudthAuthenctiationFailureHandler;
import tech.yingchuan.blogs.authentication.SudthAuthenticationSuccessHandler;
import tech.yingchuan.blogs.common.SecurityConstants;

@Configuration
public class BlogSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    protected SudthAuthenctiationFailureHandler authenctiationFailureHandler;

    @Autowired
    protected SudthAuthenticationSuccessHandler authenticationSuccessHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenctiationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                        SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM,
                        SecurityConstants.DEFAULT_LOGIN_PAGE_URL)
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
        //此代码为了解决X-Frame-Options防止网页放在iframe中，Springt Security 默认拦截
        http.headers().frameOptions().sameOrigin();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //不需要验证路径配置
        web.ignoring().antMatchers(SecurityConstants.NO_VALIDATION_REQUIRED_AFTER);
        web.ignoring().antMatchers(SecurityConstants.NO_VALIDATION_REQUIRED_COMMON);
        web.ignoring().antMatchers(SecurityConstants.NO_VALIDATION_REQUIRED_FRONT);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
